using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Client.Base;

namespace Client.Hotfix
{
    public class UGF
    {
        static private UGF instance;
        static public UGF Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new();
                }
                return instance;
            }
        }
        private readonly List<IUpdate> updates = new();
        private readonly List<IDestroy> destroys = new();
        private readonly Dictionary<Type, object> dict = new();

        public void Build()
        {
            UniApp.Instance.onUpdate = Update;
            UniApp.Instance.onDestroy = Destroy;
            InitModules();
        }

        public void Update()
        {
            for (int i = 0; i < updates.Count; i++)
            {
                updates[i].Update();
            }
        }

        public void Destroy()
        {
            updates.Clear();
            for (int i = 0; i < destroys.Count; i++)
            {
                destroys[i].Destroy();
            }
            destroys.Clear();
            dict.Clear();
            instance = null;
        }

        public T Resolve<T>() where T : class
        {
            if (dict.TryGetValue(typeof(T), out var ob))
            {
                return (T)ob;
            }
            return null;
        }

        private void InitModules()
        {
            var targetAttribute = typeof(UGFMAttribute);
            // 获取程序集
            Assembly assembly = AssemblyHelper.GetRunningAssembly("Hotfix.Runtime");
            this.Log($"{assembly}");
            if (assembly == null)
            {
                return;
            }
            var typesWithAttribute = AssemblyHelper.GetAttribute4Assembly<UGFMAttribute>("Hotfix.Runtime");
            typesWithAttribute = typesWithAttribute.OrderBy(x => x.Attribute.Weight).ToList();


            foreach (var type in typesWithAttribute)
            {
                if (dict.ContainsKey(type.Type))
                {
                    this.Log($"[ API ] - api 中已存在该服务/业务系统/玩法模式 : {type.Type.Name}");
                    continue;
                }

                var obj = Activator.CreateInstance(type.Type);

                dict.Add(type.Type, obj);

                if (obj is IAwake awake)
                {
                    awake.Awake();
                }

                if (obj is IUpdate tick)
                {
                    updates.Add(tick);
                }

                if (obj is IDestroy destroy)
                {
                    destroys.Add(destroy);
                }
            }
        }


    }

}
